package com.app.couponsharelife.ui.view

import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.widget.TextView
import com.app.couponsharelife.R

/**
 * Created by guluwa on 2018/11/6.
 */

class CustomTextView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) :
        TextView(context, attrs, defStyleAttr) {

    private var mTextSizePx = 0

    init {
        val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.CustomTextView, defStyleAttr, 0)
        mTextSizePx = typedArray.getInteger(R.styleable.CustomTextView_text_size_px, 0)
        textSize = px2sp(getDisplayMetrics(context).widthPixels * mTextSizePx / 750).toFloat()
        typedArray.recycle()
    }

    //手机屏幕宽高
    private fun getDisplayMetrics(context: Context): DisplayMetrics {
        val metric = DisplayMetrics()
        getActivity(context).windowManager.defaultDisplay.getMetrics(metric)
        return metric
    }

    private fun getActivity(c: Context): Activity {
        var context = c
        // Gross way of unwrapping the Activity so we can get the FragmentManager
        while (context is ContextWrapper) {
            if (context is Activity) {
                return context
            }
            context = context.baseContext
        }
        throw  IllegalStateException("The Context is not an Activity.")
    }

    /** px转换sp  */
    fun px2sp(pxValue: Int): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (pxValue / fontScale + 0.5f).toInt()
    }

    /** sp转换px  */
    fun sp2px(spValue: Int): Int {
        val fontScale = context.resources.displayMetrics.scaledDensity
        return (spValue * fontScale + 0.5f).toInt()
    }
}